<script setup lang="ts">
import { bindMobileApi, codeApi } from '@/api/user';
definePageMeta({
    layout: 'default-back',
    title: '修改密码',
    i18n: 'menu.updatePwd',
})
const userStore=useUserStore()
const { t } = useI18n();
const show = ref(false);
const phone = ref('');
const columns = [
    { value: 1, text: '+86' },
    { value: 2, text: '+99' },
    { value: 3, text: '+88' },
    { value: 4, text: '+77' },
    { value: 5, text: '+66' },
    { value: 6, text: '+55' },
    { value: 7, text: '+44' },
];
const showPicker = ref(false)
const curLable = ref('')
const areaCode = ref('233')
// 弹窗选中的值
const handlePickerConfirm = (selectedValues: number[]) => {
    curLable.value = (columns.find(v => v.value == selectedValues[0]))!.text
}
const getCodeBtn = async () => {
    if (phone.value) {
        show.value = true
        if(userStore.user.mobile) getSecretePhone(userStore.user.mobile)
        try {
            await codeApi({ mobile: phone.value, type: 0, areaCode: areaCode.value })
            // 获取倒计时
            getCountdownTime()
            // 获取隐藏号码

        } catch (error) {
            showFailToast('获取验证码失败！')
        }

    } else {
        showFailToast('请输入手机号！')
    }
}
// 获取隐藏手机号-10位
const getSecretePhone = (val: string) => {
    secretePhone.value= val.replace(/^(\d{3})\d+(\d{3})$/, '$1****$2');
    // return val.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')  //11位手机号
}
onMounted(() => {
    nextTick(() => {
        phoneRefs.value = phoneRefs.value.slice(0, 4);
        // if(userStore.user.mobile) getSecretePhone(userStore.user.mobile)
    });
});
// 6位数的验证码
const verifyCode = ref(["", "", "", "", "", ""]);
// 中间4位号码
const centerPhone = ref(["", "", "", ""]);
// 隐藏显示的手机号
const secretePhone = ref('')
const phoneRefs = ref([]);
const codeRefs = ref([]);
const phoneIndex = ref(0);
const codeIndex = ref(0);
const isError = ref(false);
const getCode = ref(false);
// 弹窗聚焦事件
watch(() => show.value, (val) => {
    if (val) {
        nextTick(() => {
            phoneRefs.value[0]?.focus();
        });
    }
});
// 验证码焦事件
watch(() => getCode.value, (val) => {
    if (val) {
        nextTick(() => {
            codeRefs.value[0]?.focus();
        });
    }
});
// 输入
const onInput = (index: number, type: number) => {
    if (type == 1) {
        const val = verifyCode.value[index];
        if (val && /^\d$/.test(val)) {
            // 移动焦点到下一个输入框
            if (index < 5) {
                nextTick(() => {
                    codeRefs.value[index + 1]?.focus();
                });
            }
        } else {
            verifyCode.value[index] = "";
        }
    } else {
        const val = centerPhone.value[index];
        if (/^\d$/.test(val)) {
            // 移动焦点到下一个输入框
            if (index < 3) {
                nextTick(() => {
                    phoneRefs.value[index + 1]?.focus();
                });
            }
        } else {
            centerPhone.value[index] = "";
        }
    }

};
// 删除
const onDelete = (index: number, type: number) => {
    if (type == 1) {
        if (verifyCode.value[index] === "" && index > 0) {
            nextTick(() => {
                codeRefs.value[index - 1]?.focus();
            });
        }
    } else {
        if (centerPhone.value[index] === "" && index > 0) {
            nextTick(() => {
                phoneRefs.value[index - 1]?.focus();
            });
        }
    }

};


const onlyNumber = (event: KeyboardEvent) => {
    const key = event.key;
    if (!/^\d$/.test(key)) {
        event.preventDefault(); // 阻止非数字输入
    }
};
// 弹窗取消事件
const onCancel = () => {
    centerPhone.value = ['', '', '', ''];
    isError.value = false;
    show.value = false;
};
// 打开弹窗确认事件
const handleBeforeClose = (action: string, done: () => void) => {
    if (action === 'confirm') {
        if (centerPhone.value.every(code => code !== '')) {
            const code = centerPhone.value.join('');
            console.log('验证码：', code);
            getCode.value = true
            onCancel()
            // done(); // 确认关闭
        } else {
            isError.value = true;
        }
    } else {
        onCancel()
        // done(); // 确认关闭
    }
};
// 倒计时相关的数据
const countdown = ref(60);
const isCounting = ref(false);
// 获取倒计时
const getCountdownTime = () => {
    if (isCounting.value) return;

    isCounting.value = true;
    let timer = setInterval(() => {
        if (countdown.value > 0) {
            countdown.value--;
        } else {
            clearInterval(timer);
            isCounting.value = false;
            countdown.value = 60;
        }
    }, 1000);

};
</script>

<template>
    <div mx-auto text-center text-16 text-dark dark:text-white p-15>
        <div class=" mb-10">
            <div class=" font-bold color-#ffffff">{{ getCode ? countdown == 60 ? t('my_page.setting.updatePwd.getCode')
                : t('my_page.setting.updatePwd.inputCode') : t('my_page.setting.updatePwd.phoneValid') }}</div>
            <div class="text-12 shallow my-12">{{ getCode ? countdown == 60 ?
                t('my_page.setting.updatePwd.placeGetCode') :
                t('my_page.setting.updatePwd.sendCode') : t('my_page.setting.updatePwd.placeValidCode') }}
            </div>
            <div class="text-12">{{ getCode ? phone : '' }}</div>
        </div>
        <!-- 手机号 -->
        <van-form class="outForm mb-10 mx-5" v-if="!getCode">
            <van-cell-group inset>
                <van-field v-model="phone" name="phone" :border="false" :required="false" placeholder="请填写手机号"
                    :label="'+' + areaCode">
                    <!-- <template #left-icon>
                        <span v-if="curLable || phone.length"> {{ curLable }}</span>
                    </template> -->
                    <template #right-icon>
                        <img src="/imgs/search_close.png" alt="" class="w-18" @click="phone = ''" v-if="phone">
                        <!-- <van-icon name="arrow" color="#FFFFFF" class="opacity-70" v-else @click="showPicker = true" /> -->
                    </template>
                </van-field>
            </van-cell-group>
            <div class="mt-20 w-180 mx-auto">
                <van-button block round type="primary" native-type="button" @click="getCodeBtn">
                    {{ t('my_page.setting.updatePwd.getCode') }}
                </van-button>
            </div>
        </van-form>
        <!-- 外层输入6位验证码 -->
        <div v-else>
            <van-form class="dialog6 mb-10 mx-20 flex justify-between items-center">
                <template v-for="(val, index) in verifyCode" :key="index">
                    <van-cell-group inset>
                        <van-field ref="codeRefs" v-model="verifyCode[index]" type="tel" maxlength="1"
                            :class="{ 'error-border': isError && verifyCode[index] === '' }" input-align="center"
                            class="verify-input" @input="onInput(index, 1)" @keypress="onlyNumber"
                            @keydown.delete="onDelete(index, 1)" @focus="codeIndex = index" />
                    </van-cell-group>
                </template>
            </van-form>
            <div class="color-[var(--c-primary)] text-right text-12 pr-20" @click="getCountdownTime">
                <div>
                    <div v-if="!isCounting"> {{ t('my_page.setting.updatePwd.getCode') }}</div>
                    <div v-else>{{ countdown }}s {{ t('my_page.setting.updatePwd.retry') }}</div>
                </div>
            </div>
        </div>
        <!-- 弹窗 -->
        <van-dialog v-model:show="show" :title="t('my_page.setting.updatePwd.security')" show-cancel-button
            class="dialog" :overlayStyle="{ backgroundColor: 'rgba(0, 0, 0, 0.3)' }" width="75%"
            :before-close="handleBeforeClose">
            <div class="text-12 my-10 px-12 color-#666470"> {{ t('my_page.setting.updatePwd.center4') }}</div>
            <div class="text-14 my-10 color-#0d0c11">+{{ areaCode }} {{ secretePhone }}</div>
            <van-form class="mb-10 mx-30 flex justify-between items-center">
                <template v-for="(val, index) in centerPhone" :key="index">
                    <van-cell-group inset>
                        <van-field ref="phoneRefs" v-model="centerPhone[index]" type="tel" maxlength="1"
                            :class="{ 'error-border': isError && centerPhone[index] === '' }" input-align="center"
                            class="verify-input" @input="onInput(index, 2)" @keypress="onlyNumber"
                            @keydown.delete="onDelete(index, 2)" @focus="phoneIndex = index" />
                    </van-cell-group>
                </template>
            </van-form>
        </van-dialog>
        <!-- 手机号前缀弹窗 -->
        <GamePicker v-model:show="showPicker" :columns="columns" title="选择前缀" @confirm="handlePickerConfirm" />
    </div>
</template>
<style lang="css" scoped>
.shallow {
    color: #ffffff;
    opacity: 0.6;
}

::v-deep .dialog .van-cell {
    width: 46px;
    border-radius: 6px;
    border: 1px solid #f2f2f2;
    background: #f2f1f7;
}
::v-deep .dialog6 .van-cell {
    width: 46px;
    border-radius: 6px;
    background: #303536;
    border-radius: 6px;
    color: #ffffff;
    border: solid 1px rgba(255, 255, 255, 0.15);
}
::v-deep .dialog6 .van-cell-group--inset {
    margin-right: 5px;
    border-radius: 6px;
}
::v-deep .dialog .van-cell.error-border {
    border: 1px solid #ff4d4f !important;
}

::v-deep .dialog .van-cell-group--inset {
    margin-right: 5px;
    border-radius: 6px;
}

::v-deep .dialog .van-cell-group--inset:last-child {
    margin-right: 0;
}

::v-deep .outForm .van-cell-group--inset {
    background: transparent;
}

::v-deep .outForm .van-cell {
    /* background: #f9fafc; */
    /* color: #aab2bb; */
    margin: 10px 0;
    padding: 10px 12px;
    border-radius: 8px;
    border: 1px solid #f0f1f3;

    line-height: 18px;
    background: #303536;
    border-radius: 6px;
    border: solid 1px rgba(255, 255, 255, 0.15);
}

::v-deep .outForm .van-field__control {
    color: #a1a1aa;
}

::v-deep .outForm .van-field__label {
    color: #a1a1aa;
}
</style>